/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.xfok.ui.animation;

import java.util.List;

import net.xfok.ui.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Rotate3dGrid extends Activity implements OnTouchListener {
	private static final String TAG = "Rotate3dGrid";
	private static final int ITEM_COUNT_PORT=21;
	private static final int ITEM_COUNT_LAND=20;
	private float mCenterX, mCenterY;
	private GridView grid1, grid2;
	private RotateCubeAnimation leftAnimation, rightAnimation;
	private int id = 0;
	private float xStart, xEnd;
	private int itemCount=ITEM_COUNT_LAND;
	private List<ResolveInfo>[] apps;
	private List<ResolveInfo> mApps;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rotate_3d_grid);
		grid1 = (GridView) findViewById(R.id.grid1);
		grid2 = (GridView) findViewById(R.id.grid2);
		grid1.setOnTouchListener(this);
		grid2.setOnTouchListener(this);
	}
	
	public void onResume(){
		super.onResume();
		mCenterX = getWidth(this) / 2;
		mCenterY = getHeight(this) / 2;	
		itemCount=mCenterX>mCenterY?ITEM_COUNT_LAND:ITEM_COUNT_PORT;
		loadApps();
		grid1.setAdapter(new AppsAdapter(apps[id%apps.length]));
	}

	public static int getWidth(Context cx) {
		DisplayMetrics dm = cx.getApplicationContext().getResources()
				.getDisplayMetrics();
		return dm.widthPixels;
	}

	public static int getHeight(Context cx) {
		DisplayMetrics dm = cx.getApplicationContext().getResources()
				.getDisplayMetrics();
		return dm.heightPixels;
	}
	private void setRight() {
		Log.i(TAG, "id="+id);
		if(id<0)id=id+apps.length;
		grid1.setAdapter(new AppsAdapter(apps[(id)%apps.length]));
		grid2.setAdapter(new AppsAdapter(apps[(id-1+apps.length)%apps.length]));
		id--;
		
	}
	private void setLeft() {
		Log.i(TAG, "id=" + id);
		if(id<0)id=id+apps.length;
		grid1.setAdapter(new AppsAdapter(apps[id%apps.length]));
		grid2.setAdapter(new AppsAdapter(apps[(id+1)%apps.length]));
		id++;
	}

	private void loadApps() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
		int num=mApps.size()%itemCount==0?mApps.size()/itemCount:mApps.size()/itemCount+1;
		apps=new List[num];
		for(int i=0;i<num;i++){
			int end=(i+1)*itemCount>mApps.size()?mApps.size():(i+1)*itemCount;
			apps[i]=mApps.subList(i*itemCount, end);
		}
	}

	private void rotateLeft() {
		setLeft();
		rotate(grid1,grid2,false);		
	}

	private void rotateRight() {
		setRight();
		rotate(grid1,grid2,true);	
	}

	private void rotate(View left,View right,boolean direction){
		int angel=direction?1:-1;
		leftAnimation = new RotateCubeAnimation(0, RotateCubeAnimation.RIGHT_ANGEL*angel, 0, 0, mCenterX, mCenterY);
		rightAnimation = new RotateCubeAnimation((-1)*RotateCubeAnimation.RIGHT_ANGEL*angel, 0, 0, 0, mCenterX, mCenterY);
		leftAnimation.setFillAfter(true);
		leftAnimation.setDuration(RotateCubeAnimation.ROTATE_DURATION);
		rightAnimation.setFillAfter(true);
		rightAnimation.setDuration(RotateCubeAnimation.ROTATE_DURATION);
		left.startAnimation(leftAnimation);
		right.startAnimation(rightAnimation);
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN) {
			xStart = event.getX();
		}
		if (action == MotionEvent.ACTION_UP) {
			xEnd = event.getX();
			if(xEnd!=xStart){
				if (xEnd > xStart) {
//					id++;
					rotateRight();					
				} else {
//					id--;
					rotateLeft();			
				}
			}
			xEnd = xStart = 0;
		}
		// TODO Auto-generated method stub
		return false;
	}

	public class AppsAdapter extends BaseAdapter {
		private List<ResolveInfo> mApps;
		public AppsAdapter(List<ResolveInfo> mApps) {
			this.mApps=mApps;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i;

			if (convertView == null) {
				i = new ImageView(Rotate3dGrid.this);
				i.setScaleType(ImageView.ScaleType.FIT_CENTER);
				i.setLayoutParams(new GridView.LayoutParams(50, 50));
			} else {
				i = (ImageView) convertView;
			}
			ResolveInfo info = mApps.get(position);
			i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
			return i;
		}

		public final int getCount() {
			return mApps.size();
		}

		public final Object getItem(int position) {
			return mApps.get(position);
		}

		public final long getItemId(int position) {
			return position;
		}
	}
}
